package com.kiss.rpc.compress;

import com.kiss.rpc.config.Wrapper;
import com.kiss.rpc.compress.impl.GzipCompressor;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class CompressorFactory {
    public static final ConcurrentHashMap<String, Wrapper<Compressor>> COMPRESSOR_CACHE = new ConcurrentHashMap<>();
    public static final ConcurrentHashMap<Byte, Wrapper<Compressor>> COMPRESSOR_CACHE_CODE = new ConcurrentHashMap<>();

    static {
        Wrapper<Compressor> gzipCompressorWrapper = new Wrapper<>("gzip", (byte) 1, new GzipCompressor());
        COMPRESSOR_CACHE.put(gzipCompressorWrapper.getName(), gzipCompressorWrapper);
        COMPRESSOR_CACHE_CODE.put(gzipCompressorWrapper.getCode(), gzipCompressorWrapper);
    }

    public static Wrapper<Compressor> getCompressor(byte type) {
        Wrapper<Compressor> res = COMPRESSOR_CACHE_CODE.get(type);
        if (res == null) {
            log.error("没找到对应的压缩器编码【{}】", type);
            throw new RuntimeException();
        }
        return res;
    }

    public static Wrapper<Compressor> getCompressor(String type) {
        Wrapper<Compressor> res = COMPRESSOR_CACHE.get(type);
        if (res == null) {
            log.error("没找到对应的压缩器【{}】", type);
            throw new RuntimeException();
        }
        return res;
    }
}
